package com.example.a17376046_xsh_finaltest.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.a17376046_xsh_finaltest.R;
import com.example.a17376046_xsh_finaltest.dao.MyDatabaseHelper;
import com.example.a17376046_xsh_finaltest.dao.MyloginCursor;
import com.example.a17376046_xsh_finaltest.entity.User;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends Activity implements OnClickListener {

	private EditText userName;
	private EditText passWord;
	private Button loginBtn;
	private Button loginMissps;
	private Button loginNewUser;
	private Button loginChangePw;
	private String isId, isPs;
	Response response;
	String loginInformation;
	private SQLiteOpenHelper helper;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					Toast.makeText(LoginActivity.this, "账户或密码输入错误", 0).show();
					break;
				case 1:
					Gson gson = new Gson();
					User user = gson.fromJson((String) msg.obj, User.class);
					String userName = user.getUserName();
					//Log.d("MainActivity", userName);
					int fan = user.getFan();
					//Log.d("MainActivity", fan+"");
					int attention = user.getAttention();
					//Log.d("MainActivity", attention+"");
					int post = user.getPost();
					//Log.d("MainActivity", post+"");
					Intent intent = new Intent(LoginActivity.this, MainActivity.class);
					intent.putExtra("userName", userName);
					intent.putExtra("fan", fan);
					intent.putExtra("attention", attention);
					intent.putExtra("post", post);
					startActivity(intent);
//                    loginStatus.setText(userName);
//                    myFans.setText("我的粉丝 " + fan);
//                    myConcern.setText("我的关注 " + attention);
//                    myPost.setText("我的贴子 " + post);
					break;
				case 2:
					Toast.makeText(LoginActivity.this, "当前无网络", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		helper = new MyDatabaseHelper(this);
		initView();
		Intent i = super.getIntent();
		String Id = i.getStringExtra("myId");
		userName.setText(Id);
	}
	private void initView() {
		userName =  findViewById(R.id.loginId);
		passWord =  findViewById(R.id.loginPassword);
		loginBtn =  findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(this);
		loginMissps = findViewById(R.id.loginMissps);
		loginMissps.setOnClickListener(this);
		loginNewUser =  findViewById(R.id.loginNewUser);
		loginNewUser.setOnClickListener(this);
		loginChangePw = findViewById(R.id.loginChangePw);
		loginChangePw.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.loginBtn:
			if (ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.INTERNET}, 4);
			} else {
				userLogin();
			}
		/*	isId = userName.getText().toString();
			isPs = passWord.getText().toString();
			if (new MyloginCursor(
					LoginActivity.this.helper.getReadableDatabase()).find(isId)
					.size() == 0) {
				Toast.makeText(LoginActivity.this, "手机号未注册，请注册后登录",
						Toast.LENGTH_SHORT).show();
			} else {
				String lph = new MyloginCursor(
						LoginActivity.this.helper.getReadableDatabase()).find(
						isId).toString();
				String result[] = lph.split(",");
				if (result[1].equals(isId) && result[2].equals(isPs)) {
					Intent intent4 = new Intent(LoginActivity.this,
							MainActivity.class);
					if (getPackageManager().resolveActivity(intent4, PackageManager.MATCH_DEFAULT_ONLY) != null) {
						startActivity(intent4);
					}else {
						Toast.makeText(LoginActivity.this, "页面已丢失",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(LoginActivity.this, "用户名或密码错误",
							Toast.LENGTH_SHORT).show();
				}
			}*/
			break;
		case R.id.loginMissps:
			Intent intent1 = new Intent(LoginActivity.this,
					FindPasswordActivity.class);
			if (getPackageManager().resolveActivity(intent1, PackageManager.MATCH_DEFAULT_ONLY) != null) {
				startActivity(intent1);
			}else {
				Toast.makeText(LoginActivity.this, "页面已丢失",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.loginNewUser:
			Intent intent2 = new Intent(LoginActivity.this, RegisterActivity.class);
			if (getPackageManager().resolveActivity(intent2, PackageManager.MATCH_DEFAULT_ONLY) != null) {
				startActivity(intent2);
			}else {
				Toast.makeText(LoginActivity.this, "页面已丢失",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.loginChangePw:
			Intent intent3 = new Intent(LoginActivity.this,
					ChangePasswordActivity.class);
			if (getPackageManager().resolveActivity(intent3, PackageManager.MATCH_DEFAULT_ONLY) != null) {
				startActivity(intent3);
			}else {
				Toast.makeText(LoginActivity.this, "页面已丢失",
						Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	private void userLogin() {
		if ((userName.getText().toString().length() == 0 || userName.getText().toString() == null)
				|| !userName.getText().toString().equals(stringFilter(userName.getText().toString()))) {
			Toast.makeText(LoginActivity.this, "不能输入非法字符！！！", 0).show();
		} else {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						OkHttpClient client = new OkHttpClient();
						RequestBody requestBody = new FormBody.Builder()
								.add("userName", userName.getText().toString())
								.add("passWord", passWord.getText().toString())
								.build();
						Request request = new Request.Builder()
								.url("http://106.13.133.171/17376016_gy_StudyGo/login")
								.post(requestBody)
								.build();
						response = client.newCall(request).execute();
						loginInformation = response.body().string();
						if (loginInformation.equals("0")) {
							Message message = new Message();
							message.what = 0;
							handler.sendMessage(message);
						} else {
//                            Log.d("MainActivity", "这里是1");
							Message message = new Message();
							message.what = 1;
							message.obj = loginInformation;
//                            Log.d("MainActivity", "这里是2");
							handler.sendMessage(message);
//                            Log.d("MainActivity", "这里是3");
						}
						//Log.d("MainActivity", "没有错误" + registrationUserName.getText());
					} catch (IOException e) {
						e.printStackTrace();
						Message message = new Message();
						message.what = 2;
						handler.sendMessage(message);
					}
				}
			}).start();
		}
	}
	public static String stringFilter(String str) throws PatternSyntaxException {
		String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
		Pattern pattern = Pattern.compile(regEx);
		Matcher m = pattern.matcher(str);
		return m.replaceAll("").trim();
	}
}
